#!/usr/bin/perl

package Swignition::MagicString;
use strict;
use Exporter;
use overload '""'=>\&to_string, '.'=>\&concat, 'cmp'=>\&compare;
our @ISA    = qw(Exporter);
our @EXPORT = qw(ms msat isms strlang);

sub new
{
	my $class = shift;
	my $rv    = {};
	
	$rv->{string} = shift;
	bless $rv, $class;
}

sub to_string
{
	my $this = shift;
	return $this->{string};
}

sub strlang
{
	my $str     = shift;
	my $lang    = shift;
	my $rv      = Swignition::MagicString->new($str);
	$rv->{lang} = $lang;
	return $rv;
}

sub TO_JSON
{
	my $this = shift;
	return $this->{string};
}

sub concat
{
	my $a = shift;
	my $b = shift;
	my $rev = shift;
	
	if ($rev)
	{
		my $rev = $a;
		$a = $b;
		$b = $rev;
	}

	unless (ref $a)
		{ $a = { string => $a }; }
	unless (ref $b)
		{ $b = { string => $b }; }
	
	my $rv = {};
	$rv->{string} = $a->{string}.$b->{string};

	if (!$b->{lang} || (lc($a->{lang}) eq lc($b->{lang})))
	{
		$rv->{lang} = $a->{lang};
	}
	
	bless $rv, 'Swignition::MagicString';
}

sub ms
{
	my ($rv, $dom);

	$rv->{string} = shift;
	$dom          = shift || return $rv->{string};
	
	$rv->{lang}   = $dom->getAttribute('_xmllang');
	$rv->{xpath}  = $dom->getAttribute('_xpath');
	$rv->{xml}    = $dom->toString;
	$rv->{dom}    = $dom;
	
	bless $rv, 'Swignition::MagicString';
}

sub msat
{
	my ($rv, $dom);

	$rv->{string} = shift;
	$dom          = shift || return $rv->{string};
	
	$rv->{lang}   = $dom->getAttribute('_xmllang');
	$rv->{xpath}  = $dom->getAttribute('_xpath');
	
	bless $rv, 'Swignition::MagicString';
}

sub compare
{
	my $a = shift;
	my $b = shift;
	return "$a" cmp "$b";
}

sub isms
{
	my $this = shift;
	return ('Swignition::MagicString' eq ref $this);
}

1;
